package cl.parser.internal;

import java.util.ArrayList;
import java.util.List;

import cl.parser.IParseNode;
import cl.parser.external.ElseKeywordNode;
import cl.parser.external.IfKeywordNode;

public class IfNode extends InternalNode implements IFat {

    @Override
    public String prettyPrint(String indent) {
        String res = "if" + children.get(0).prettyPrint(indent) + " ";
        
        if(children.get(1) instanceof CodeBlockNode) {
            res += children.get(1).prettyPrint(indent);
        } else {
            res += "\n" + children.get(1).prettyPrint(indent + "    ");
        }
        
        if(children.size() > 2) {
            if(((InternalNode)children.get(2)).children.get(0) instanceof IfNode) {
                res += " else " + ((InternalNode)children.get(2)).children.get(0).prettyPrint(indent);
            } else {
                res += indent + "else\n" + children.get(2).prettyPrint(indent + "    ");
            }
        }
        
        return res;
    }
    
    @Override
    protected List<IParseNode> getAllowed(IParseNode last, List<IParseNode> soFar) {
        List<IParseNode> allowed = new ArrayList<IParseNode>();
        
        if(last == null) {
            allowed.add(new IfKeywordNode());
        } else if(last instanceof IfKeywordNode) {
            allowed.add(new ConditionNode());
        } else if(last instanceof ConditionNode) {
            allowed.add(new CodeBlockNode());
            allowed.add(new StatementNode());
        } else if((last instanceof CodeBlockNode ||
                  last instanceof StatementNode) &&
                  soFar.size() == 3) {
            allowed.add(new ElseKeywordNode());
        } else if(last instanceof ElseKeywordNode) {
            allowed.add(new CodeBlockNode());
            allowed.add(new StatementNode());
        }
        
        return allowed;
    }

    @Override
    protected boolean isValid(IParseNode last, List<IParseNode> soFar) {
        return last instanceof CodeBlockNode ||
               last instanceof StatementNode;
    }

    @Override
    public void loseWeight() {
        // remove if
        children.remove(0);
        
        // remove else
        if(children.size() > 2) {
            children.remove(2);
        }
        
    }

}
